package person.twj.securitysessionredis.domain.vo;

import com.fasterxml.jackson.databind.ObjectMapper;
import jakarta.servlet.http.HttpServletResponse;
import lombok.Builder;
import lombok.Data;

import java.io.IOException;
import java.util.HashMap;
import java.util.Map;
import java.util.function.Consumer;

@Data
@Builder
//@FieldNameConstants
public class RsVo {
    private Integer status;
    private Integer code;
    private String message;
    private Object data;

    public static RsVo success(String message,Object data){
        return RsVo.builder()
                .status(1)
                .code(0)
                .message(message)
                .data(data)
                .build();
    }
    public static RsVo success(String message, Consumer<Map<String, Object>> consumer){
        Map<String, Object> map = new HashMap<>();
        consumer.accept(map);
        return RsVo.builder()
                .status(1)
                .code(0)
                .message(message)
                .data(map)
                .build();
    }

    public static RsVo success(String message){
        return success(message, null);
    }
    public static RsVo failed(Integer code,String message){
        return RsVo.builder()
                .status(0)
                .code(code)
                .message(message)
                .data(null)
                .build();
    }
    public static RsVo failed(Integer code,String message,Object data){
        return RsVo.builder()
                .status(0)
                .code(code)
                .message(message)
                .data(data)
                .build();
    }

    public static RsVo failed(String message){
        return failed(-1,message);
    }

    public void writeTo(HttpServletResponse response) throws IOException {
        response.setContentType("application/json;charset=utf-8");
        response.getWriter().write(new ObjectMapper().writeValueAsString(this));
    }


}
